package com.csi.okr.common.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 微信基本信息
 * @author 张鹏
 *
 */
public class WxUtil {
	
	//微信回调网址
	public static final String DOMAIN = "http://okr.yanxishe.cc/okr";
	
	//企业号ID
	public static final String CORPID = "wx05ce5c1b90e25d74";
	
	//企业号权限组密钥
	public static final String CORPSECRET = "wPua1R_zNGjX8Aa_iGAJbgZUO0yoONot_uAOr2wB37OO3X9v7iPvxJhQ9Z3KRLNN";
	
	public static Map<String, Object> ACCESS_TOKEN = new HashMap<String, Object>();

	
	/**
	 * 获取本地token
	 * @return
	 */
	public static String getToken(){
		
		Long TIMESTAMP = (Long) ACCESS_TOKEN.get("TIMESTAMP");
		
		if(TIMESTAMP == null){
			return takeToken();
		}
		
		long time = System.currentTimeMillis() - TIMESTAMP;
		
		if(time > 7200000){
			return takeToken();
		}else{
			return (String) ACCESS_TOKEN.get("ACCESS_TOKEN");
		}
	}
	
	/**
	 * 到微信获取token
	 * @return
	 */
	private static String takeToken(){
		//请求Token的URL
		String url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid="+CORPID+"&corpsecret="+CORPSECRET;
		//返回结果
		String r = HttpRequestUtil.sendGet(url);
		//变为json格式
		JSONObject json = JSONObject.parseObject(r);
		//获取access_token
		String access_token = json.getString("access_token");
		//储存
		ACCESS_TOKEN.put("ACCESS_TOKEN", access_token);
		ACCESS_TOKEN.put("TIMESTAMP", System.currentTimeMillis());
		return access_token;
		
	}


	/**
	 * 获取用户UID
	 * @param code
	 * @return
	 */
	public static String getEmplCode(String code){
		
		//请求用户Uid的URL
		String url = "https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo?access_token="+getToken()+"&code="+code;
		//返回结果
		String r = HttpRequestUtil.sendGet(url);
		//变为json格式
		JSONObject json = JSONObject.parseObject(r);
		//获取access_token
		String userId = json.getString("UserId");
		return userId;
	}
}
